/*
 * @lc app=leetcode.cn id=5 lang=java
 *
 * [5] 最长回文子串
 */

// @lc code=start

import java.util.ArrayList;
import java.util.List;

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        int strLen = s.length();
        int left = 0;
        int right = 0;
        int len = 1;
        int maxStart = 0;
        int maxLen = 0;
        for (int i = 0; i < strLen; i++) {
            left = i - 1;
            right = i + 1;
            while (left >= 0 && s.charAt(left) == s.charAt(i)) {
                len++;
                left--;
            }
            while (right < strLen && s.charAt(right) == s.charAt(i)) {
                len++;
                right++;
            }
            while (left >= 0 && right < strLen && s.charAt(right) == s.charAt(left)) {
                len = len + 2;
                left--;
                right++;
            }
            if (len > maxLen) {
                maxLen = len;
                maxStart = left;
            }
            len = 1;
        }

        return s.substring(maxStart + 1, maxStart + maxLen + 1);

        // int strLen = s.length();
        // String longStr = String.valueOf(s.charAt(0));
        // for (int start = 0; start < strLen; start++) {
        //     for (int end = strLen; end > start + 1; end--) {
        //         String sslice = s.substring(start, end);
        //         if (isPalindrome(sslice)) {
        //             if (sslice.length() > longStr.length()) {
        //                 longStr = sslice;
        //             }
        //         }
        //     }
        // }
        // return longStr;
    }

    List<String> hasSet = new ArrayList<>();

    /**
     * 判断是否回文
     * 
     * @param s
     * @return
     */
    public Boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return false;
        }
        if (hasSet.indexOf(s) > -1) {
            return true;
        }
        int len = s.length();
        for (int i = 0; i < len / 2; i++) {
            if (s.charAt(i) != s.charAt(len - i - 1)) {
                return false;
            }
        }
        hasSet.add(s);
        return true;
    }
}
// @lc code=end
